let utils = require('../../utils/utils');
let bmap = require('../../libs/bmap-wx.js')
let globalData = getApp().globalData
const key = globalData.key
Page({
  data: {
    isIPhoneX: globalData.isIPhoneX,
    message: '加班的时间才刚刚开始',
    cityDatas: {},
    hourlyDatas: [],
    weatherIconUrl: globalData.weatherIconUrl,
    detailsDic: {
      key: ['tmp', 'fl', 'hum', 'pcpn', 'wind_dir', 'wind_deg', 'wind_sc', 'wind_spd', 'vis', 'pres', 'cloud', ''],
      val: {
        tmp: '温度(℃)',
        fl: '体感温度(℃)',
        hum: '相对湿度(%)',
        pcpn: '降水量(mm)',
        wind_dir: '风向',
        wind_deg: '风向角度(deg)',
        wind_sc: '风力(级)',
        wind_spd: '风速(mk/h)',
        vis: '能见度(km)',
        pres: '气压(mb)',
        cloud: '云量',
      },
    },
    lifestyles: {
      'comf': '舒适度指数',
      'cw': '洗车指数',
      'drsg': '穿衣指数',
      'flu': '感冒指数',
      'sport': '运动指数',
      'trav': '旅游指数',
      'uv': '紫外线指数',
      'air': '空气污染扩散条件指数',
      'ac': '空调开启指数',
      'ag': '过敏指数',
      'gl': '太阳镜指数',
      'mu': '化妆指数',
      'airc': '晾晒指数',
      'ptfc': '交通指数',
      'fsh': '钓鱼指数',
      'spi': '防晒指数',
    },
    // 用来清空 input
    searchText: '',
    // 是否已经弹出
    // 是否已经弹出
    hasPopped: false,
    animationMain: {},
    animationOne: {},
    animationTwo: {},
    animationThree: {},
    // 是否切换了城市
    located: true,
    // 需要查询的城市
    searchCity: '',
    bcgImgList: [{
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg1.jpg',
        topColor: '#004a89'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg2.jpg',
        topColor: '#d6d1e6'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg3.jpg',
        topColor: '#2d2225'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg4.jpg',
        topColor: '#009ffe'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg5.jpg',
        topColor: '#0085e5'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg6.jpg',
        topColor: '#b8bab9'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg7.jpg',
        topColor: '#393836'
      },
      {
        src: 'cloud://pets-7guwp737b4dd6219.7065-pets-7guwp737b4dd6219-1304125172/weatherbg/bg8.jpg',
        topColor: '#ffa5bc'
      }
    ],
    bcgImgIndex: 0,
    bcgImg: '',
    bcgImgAreaShow: false,
    bcgColor: '#393836',
    // 粗暴直接：移除后再创建，达到初始化组件的作用
    showHeartbeat: true,
    // heartbeat 时禁止搜索，防止动画执行
    enableSearch: true,
    openSettingButtonShow: false,
  },


  commitSearch(res) {
    let val = ((res.detail || {}).value || '').replace(/\s+/g, '')
    this.search(val)
  },
  dance() {
    this.setData({
      enableSearch: false,
    })
    let heartbeat = this.selectComponent('#heartbeat')
    heartbeat.dance(() => {
      this.setData({
        showHeartbeat: false,
        enableSearch: true,
      })
      this.setData({
        showHeartbeat: true,
      })
    })
  },
  clearInput() {
    this.setData({
      searchText: '',
    })
  },
  search(val, callback) {
    if (val === '520' || val === '521' || val === '殷斓溱') {
      this.clearInput()
      this.dance()
      return
    }
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    })
    if (val) {
      this.setData({
        located: false,
      })
      this.getCity(val)
    }
    callback && callback()
  },
  getCity: function (val) {
    var that = this;
    var BMap = new bmap.BMapWX({
      ak: 'L2gPxbsFywGaCQIIhPKDYzFgcsEPS3I5'
    });
    BMap.geocoding({
      address: val,
      success: function (res) {
        that.clearInput()
        let latitude = res.result.location.lat;
        let longitude = res.result.location.lng;
        that.getWeather(`${latitude},${longitude}`);
      },
      fail: function () {
        wx.showToast({
          title: '查询失败',
          icon: 'none',
        })
      },
    });
  },
  onPullDownRefresh() {
    this.reloadPage()
  },
  setBcgImg(index) {
    if (index !== undefined) {
      this.setData({
        bcgImgIndex: index,
        bcgImg: this.data.bcgImgList[index].src,
        bcgColor: this.data.bcgImgList[index].topColor,
      })
      this.setNavigationBarColor()
      return
    }
    wx.getStorage({
      key: 'bcgImgIndex',
      success: (res) => {
        let bcgImgIndex = res.data || 0
        this.setData({
          bcgImgIndex,
          bcgImg: this.data.bcgImgList[bcgImgIndex].src,
          bcgColor: this.data.bcgImgList[bcgImgIndex].topColor,
        })
        this.setNavigationBarColor()
      },
      fail: () => {
        this.setData({
          bcgImgIndex: 0,
          bcgImg: this.data.bcgImgList[0].src,
          bcgColor: this.data.bcgImgList[0].topColor,
        })
        this.setNavigationBarColor()
      },
    })
  },
  setNavigationBarColor(color) {
    let bcgColor = color || this.data.bcgColor
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.bcgColor,
    })
  },
  onLoad() {
    this.reloadPage()
    this.getLocation();
    var date = new Date();
    var h = date.getHours();
    let message = "";
    if (0 < h && h < 7) {
      message = "孤单一个人睡不着就想想鬼故事，这样你会觉得屋子充满了人。";
    } else if (7 <= h && h < 9) {
      message = "又是元气满满的一天。"
    } else if (h >= 9 && h < 11) {
      message = "划了一上午水也该干点活啦。";
    } else if (h >= 11 && h < 13) {
      message = "还没吃午饭吧，再饿一会儿等晚上一顿。"
    } else if (h >= 13 && h < 18) {
      message = "又是快乐的划水时间。";
    } else {
      message = "不到下班不工作的加班King";
    }
    this.setData({
      message: message
    });
  },

  //获取经纬度方法
  getLocation: function () {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res);
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.getWeather(`${latitude},${longitude}`)
      },
      fail: function () {
        wx.showToast({
          title: '小程序获取坐标失败，请手动输入地址查询或设置允许使用地理位置',
          icon: 'none',
        })
        that.getCityDatas();
      }
    })
  },
  // 获取缓存信息
  getCityDatas() {
    let cityDatas = wx.getStorage({
      key: 'cityDatas',
      success: (res) => {
        this.setData({
          cityDatas: res.data,
        })
      },
    })
  },
  //获取天气信息
  getWeather(location) {
    wx.request({
      url: `${globalData.requestUrl.weather}`,
      data: {
        location,
        key,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          let data = res.data.HeWeather6[0];
          console.log(data);
          if (data.status === 'ok') {
            this.clearInput()
            this.success(data, location)
          } else {
            wx.showToast({
              title: '查询失败',
              icon: 'none',
            })
          }
        }
      },
      fail: () => {
        wx.showToast({
          title: '查询失败',
          icon: 'none',
        })
      },
    })
  },
  success(data, location) {
    this.setData({
      openSettingButtonShow: false,
      searchCity: location,
    })
    wx.stopPullDownRefresh()
    let now = new Date()
    // 存下来源数据
    data.updateTime = now.getTime()
    data.updateTimeFormat = utils.formatDate(now, "MM-dd hh:mm")
    wx.setStorage({
      key: 'cityDatas',
      data,
    })
    this.setData({
      cityDatas: data,
    })
  },
  reloadPage() {
    this.setBcgImg()
  },
  showBcgImgArea() {
    this.setData({
      bcgImgAreaShow: true,
    })
  },
  hideBcgImgArea() {
    this.setData({
      bcgImgAreaShow: false,
    })
  },
  chooseBcg(e) {
    let dataset = e.currentTarget.dataset
    let src = dataset.src
    let index = dataset.index
    this.setBcgImg(index)
    wx.setStorage({
      key: 'bcgImgIndex',
      data: index,
    })
  },
  menuHide() {
    if (this.data.hasPopped) {
      this.takeback()
      this.setData({
        hasPopped: false,
      })
    }
  },
  menuMain() {
    if (!this.data.hasPopped) {
      this.popp()
      this.setData({
        hasPopped: true,
      })
    } else {
      this.takeback()
      this.setData({
        hasPopped: false,
      })
    }
  },
  popp() {
    let animationMain = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationOne = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationTwo = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationThree = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationFour = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    animationMain.rotateZ(180).step()
    animationOne.translate(0, -60).rotateZ(360).opacity(1).step()
    animationTwo.translate(-Math.sqrt(3600 - 400), -30).rotateZ(360).opacity(1).step()
    animationThree.translate(-Math.sqrt(3600 - 400), 30).rotateZ(360).opacity(1).step()
    animationFour.translate(0, 60).rotateZ(360).opacity(1).step()
    this.setData({
      animationMain: animationMain.export(),
      animationOne: animationOne.export(),
      animationTwo: animationTwo.export(),
      animationThree: animationThree.export(),
      animationFour: animationFour.export(),
    })
  },
  takeback() {
    let animationMain = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationOne = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationTwo = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationThree = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    let animationFour = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out'
    })
    animationMain.rotateZ(0).step();
    animationOne.translate(0, 0).rotateZ(0).opacity(0).step()
    animationTwo.translate(0, 0).rotateZ(0).opacity(0).step()
    animationThree.translate(0, 0).rotateZ(0).opacity(0).step()
    animationFour.translate(0, 0).rotateZ(0).opacity(0).step()
    this.setData({
      animationMain: animationMain.export(),
      animationOne: animationOne.export(),
      animationTwo: animationTwo.export(),
      animationThree: animationThree.export(),
      animationFour: animationFour.export(),
    })
  },
  menuToAbout () {
    this.menuMain()
    wx.navigateTo({
      url: '/pages/aboutwang/aboutwang',
    })
  },
})